package net.esj.basic.dao.ann;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import net.esj.basic.dao.jdbc.annotation.JColumn;
import net.esj.basic.dao.jdbc.exception.JdbcSqlInitException;

import org.springframework.util.StringUtils;

public abstract class InitializationSelection implements Serializable, Cloneable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -262457693099254986L;

	private String selectionStr;
	
	private String fromStr;
	
	private String whereStr;
	
	private Map<String,TableSel> tables = new HashMap<String,TableSel>();
	
	void generateSelection(){
		for(Field field:this.getClass().getFields()){
			if(field.isAnnotationPresent(JColumn.class)){
				JColumn column = field.getAnnotation(JColumn.class);
				int position = column.position();
				String columnName = column.name();
				String tableName = column.table();
				
				if(!StringUtils.hasText(columnName) || !StringUtils.hasText(tableName)){
					throw new JdbcSqlInitException("表名或列名不存在");
				}

				String alias = tableName.toLowerCase()+"_"+position;
				String columnAlias = columnName.toLowerCase()+"_"+position;
				ColumnSel sel = new ColumnSel(columnName, columnAlias);
				if(tables.containsKey(alias)){
					tables.get(alias).addColumn(sel);
				}else{
					TableSel table = new TableSel(tableName, alias);
					table.addColumn(sel);
					tables.put(alias,table);
				}
			
			}
		}
	}
	
	private static class TableSel implements Serializable{
		private String table;
		private String tableAlias;
		
		private Set<ColumnSel> columns;
		public TableSel(String table, String tableAlias) {
			super();
			this.table = table;
			this.tableAlias = tableAlias;
			columns = new HashSet<ColumnSel>();
		}
		public String getTable() {
			return table;
		}
		public void setTable(String table) {
			this.table = table;
		}
		public String getTableAlias() {
			return tableAlias;
		}
		public void setTableAlias(String tableAlias) {
			this.tableAlias = tableAlias;
		}
		
		public void addColumn(ColumnSel sel){
			columns.add(sel);
		}
	}
	
	private static class ColumnSel implements Serializable{
		private String column;
		private String columnAlias;
		
		public ColumnSel(String column, String columnAlias) {
			super();
			this.column = column;
			this.columnAlias = columnAlias;
		}
		public String getColumn() {
			return column;
		}
		public void setColumn(String column) {
			this.column = column;
		}
		public String getColumnAlias() {
			return columnAlias;
		}
		public void setColumnAlias(String columnAlias) {
			this.columnAlias = columnAlias;
		}
		
	}
}

